package middleware

import (
	"api/internal/types"
	"api/pkg"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

type AuthMiddleware struct {
}

func NewAuthMiddleware() *AuthMiddleware {
	return &AuthMiddleware{}
}

func (m *AuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		token := r.Header.Get("token")
		if token == "" {
			httpx.OkJsonCtx(r.Context(), w, &types.Response{
				Code:    500,
				Message: "未登录",
				Date:    nil,
			})
			return
		}
		getToken, err := pkg.GetToken(token)
		if err != nil {
			httpx.OkJsonCtx(r.Context(), w, &types.Response{
				Code:    500,
				Message: err.Error(),
				Date:    nil,
			})
			return
		}
		r.ParseForm()
		r.Form.Set("userId", getToken["user"].(string))
		// Passthrough to next handler if need
		next(w, r)
	}
}
